﻿using HalconDotNet;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl;
using ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl.Object;
using ZRFCore.Tool;
using MultiAxisAssembly;
using System.Threading.Tasks;
using System.Threading;
using ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl.Path;

namespace 喷点胶机
{
    public partial class Page_3_XldPathEdit : UIPage
    {
        private ControlMaster controlMaster;
        private PathType drawGrueType = PathType.None;
        private PathColor drawPathColor = PathColor.none;
        private List<XldPathInfo> xldPathInfos;
        private int SpurtGlueWidth;
        private int GlueWidth;

        public Page_3_XldPathEdit(ControlMaster controlMaster)
        {
            InitializeComponent();
            this.controlMaster = controlMaster;
            this.xldPathInfos = controlMaster.XldPathInfos;
            //controlMaster.XldPaths = zrf_hWindow1.XldPaths;
            
            zrf_hWindow1.AddXldPathEvent += Zrf_hWindow1_AddXldPathEvent;
            zrf_hWindow1.DeleteXldPathEvent += Zrf_hWindow1_DeleteXldPathEvent;
            zrf_hWindow1.ActiveXldPathEvent += Zrf_hWindow1_ActiveXldPathEvent; ;
            zrf_hWindow1.RepaintEvent += Zrf_hWindow1_RepaintEvent;
            zrf_hWindow1.SendToBack();
            watchForm.FormHide += WatchForm_FormHide;
            //this.KeyDown += controlMaster.MulitAxisMasterControl.KeyDown;
            //this.KeyUp += controlMaster.MulitAxisMasterControl.KeyUp;
        }

        private void WatchForm_FormHide(object? sender, EventArgs e)
        {
            controlMaster.CancelGluingTest();
        }

        private void Zrf_hWindow1_ActiveXldPathEvent(ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl.Path.XldPath? activeXldPath, int activeIndex)
        {
            if (activeIndex > -1)
            {
                btShield.FillColor = xldPathInfos[activeIndex].Shield ? Color.Red : Color.Green;
                btShield.Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield ? "取消屏蔽" : "屏蔽";
                uiTextBox1.Text = xldPathInfos[activeIndex].Delay_DelayToOutGlue.ToString();
                uiTextBox2.Text = xldPathInfos[activeIndex].Delay_OutGlueToStartMove.ToString();
                uiTextBox3.Text = xldPathInfos[activeIndex].Delay_StopGlueDelayTime.ToString();
                uiTextBox4.Text = xldPathInfos[activeIndex].Speed.ToString();
                uiTextBox5.Text = xldPathInfos[activeIndex].PlaneHeight.ToString();

                btShield.Enabled = true;
                uiTextBox1.Enabled = true;
                uiTextBox2.Enabled = true;
                uiTextBox3.Enabled = true;
                uiTextBox4.Enabled = true;
                uiTextBox5.Enabled = true;
                btGlueOutTest.Enabled = true;
                btCloseGlueTest.Enabled = true;
            }
            else
            {
                btShield.Enabled = false;
                uiTextBox1.Enabled = false;
                uiTextBox2.Enabled = false;
                uiTextBox3.Enabled = false;
                uiTextBox4.Enabled = false;
                uiTextBox5.Enabled = false;
                btGlueOutTest.Enabled = false;
                btCloseGlueTest.Enabled = false;
                uiTextBox1.Text = String.Empty;
                uiTextBox2.Text = String.Empty;
                uiTextBox3.Text = String.Empty;
                uiTextBox4.Text = String.Empty;
                uiTextBox5.Text = String.Empty;
            }

        }

        private void Zrf_hWindow1_RepaintEvent(HWindow? window)
        {
            if (zrf_hWindow1.ActiveXldPathIndex > -1)
            {
                HXLD xld = zrf_hWindow1.XldPaths[zrf_hWindow1.ActiveXldPathIndex].XLD;
                HRegion hRegion;
                switch (xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Type)
                {
                    case PathType.None:
                        hRegion = new HRegion();
                        hRegion.GenEmptyRegion();
                        break;
                    case PathType.Glue:
                        hRegion = GenRegionFromXld(xld, GlueWidth);
                        break;
                    case PathType.SpurtGlue:
                        hRegion = GenRegionFromXld(xld, SpurtGlueWidth);
                        break;
                    case PathType.AvoidPath:
                        hRegion = new HRegion();
                        hRegion.GenEmptyRegion();
                        break;
                    default:
                        hRegion = new HRegion();
                        hRegion.GenEmptyRegion();
                        break;
                }
                HRegionWithColor hRegionWithColor = new HRegionWithColor(hRegion, zrf_hWindow1.XldPaths[zrf_hWindow1.ActiveXldPathIndex].Color);
                zrf_hWindow1.HRegions[zrf_hWindow1.ActiveXldPathIndex] = hRegionWithColor;
            }
        }

        private HRegion GenRegionFromXld(HXLD xld, int width)
        {
            if (xld != null && xld.IsInitialized())
            {
                HOperatorSet.GetContourXld(xld, out HTuple row, out HTuple column);
                HOperatorSet.GenRegionPolygon(out HObject region, row, column);
                HOperatorSet.DilationCircle(region, out HObject region1, width);
                return new HRegion(region1);
            }
            else
            {
                HRegion hRegion = new HRegion();
                hRegion.GenEmptyRegion();
                return hRegion;
            }
        }

        private void Zrf_hWindow1_DeleteXldPathEvent(List<ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl.Path.XldPath> deletedXldPaths, int deletedIndex)
        {
            xldPathInfos.RemoveAt(deletedIndex);
            zrf_hWindow1.HRegions.RemoveAt(deletedIndex);
        }

        private void Zrf_hWindow1_AddXldPathEvent(List<ZRFCore.MachineVisionAlgorithm.Controls.ZrfWindowControl.Path.XldPath> addedXldPaths, int addIndex)
        {
            XldPathInfo xldPathInfo = new XldPathInfo()
            {
                Shield = false,
                Color = drawPathColor,
                Type = drawGrueType,
                Delay_DelayToOutGlue = 0,
                Delay_OutGlueToStartMove = 0,
                Delay_StopGlueDelayTime = 0,
                Speed = 20,
            };
            xldPathInfos.Add(xldPathInfo);
            HXLD xld = addedXldPaths[addIndex].XLD;
            HRegion hRegion;
            switch (xldPathInfo.Type)
            {
                case PathType.None:
                    hRegion = new HRegion();
                    hRegion.GenEmptyRegion();
                    break;
                case PathType.Glue:
                    hRegion = GenRegionFromXld(xld, GlueWidth);
                    xldPathInfo.PlaneHeight = controlMaster.GlueDefaultHeight;
                    xldPathInfo.ZPlanePos = controlMaster.GlueClosePlaneZpos;
                    //xldPathInfo.SnapPosX = controlMaster.SnapPosX;
                    //xldPathInfo.SnapPosY = controlMaster.SnapPosY;
                    //xldPathInfo.SnapPosZ = controlMaster.SnapPosZ;
                    xldPathInfo.MachCoordDeviationX = controlMaster.GlueHeadDeviationX;
                    xldPathInfo.MachCoordDeviationY = controlMaster.GlueHeadDeviationY;
                    break;
                case PathType.SpurtGlue:
                    hRegion = GenRegionFromXld(xld, SpurtGlueWidth);
                    xldPathInfo.PlaneHeight = controlMaster.SpurtGlueDefaultHeight; ;
                    xldPathInfo.ZPlanePos = controlMaster.SpurtGlueClosePlaneZpos;
                    //xldPathInfo.SnapPosX = controlMaster.SnapPosX;
                    //xldPathInfo.SnapPosY = controlMaster.SnapPosY;
                    //xldPathInfo.SnapPosZ = controlMaster.SnapPosZ;
                    xldPathInfo.MachCoordDeviationX = controlMaster.SpurtGlueHeadDeviationX;
                    xldPathInfo.MachCoordDeviationY = controlMaster.SpurtGlueHeadDeviationY;
                    break;
                case PathType.AvoidPath:
                    hRegion = new HRegion();
                    hRegion.GenEmptyRegion();
                    break;
                default:
                    hRegion = new HRegion();
                    hRegion.GenEmptyRegion();
                    break;
            }
            HRegionWithColor hRegionWithColor = new HRegionWithColor(hRegion, addedXldPaths[addIndex].Color);
            zrf_hWindow1.HRegions.Add(hRegionWithColor);
        }

        private void Page_3_XldPathEdit_Initialize(object sender, EventArgs e)
        {
            zrf_hWindow1.XldPaths = controlMaster.XldPaths;
            xldPathInfos = controlMaster.XldPathInfos;
            zrf_hWindow1.HRegions = controlMaster.XldPathRegions;
            zrf_hWindow1.Image = controlMaster.StandardImg;
            
            SpurtGlueWidth = controlMaster.SpurtGlueWidth;
            GlueWidth = controlMaster.GlueWidth;
            Task.Run(() =>
            {
                Thread.Sleep(500);
                this.Invoke(new Action(() =>
                {
                    this.Focus();//设置焦点
                }));
            });
        }

        private void Page_3_XldPathEdit_Finalize(object sender, EventArgs e)
        {
            if (zrf_hWindow1.Image == null || !zrf_hWindow1.Image.IsInitialized())
            {
                return;
            }

        }

        private void btDrawSpurtGluePath_Click(object sender, EventArgs e)
        {
            drawGrueType = PathType.SpurtGlue;
            drawPathColor = PathColor.blue;
            btDrawPoint.FillColor = ((UIButton)sender).FillColor;
            btDrawLine.FillColor = ((UIButton)sender).FillColor;
            btDrawCircle.FillColor = ((UIButton)sender).FillColor;
            btDrawPoint.Visible = true;
            btDrawLine.Visible = true;
            btDrawCircle.Visible = true;
            btExitDraw.Visible = true;
        }

        private void btDrawGluePath_Click(object sender, EventArgs e)
        {
            drawGrueType = PathType.Glue;
            drawPathColor = PathColor.magenta;
            btDrawPoint.FillColor = ((UIButton)sender).FillColor;
            btDrawLine.FillColor = ((UIButton)sender).FillColor;
            btDrawCircle.FillColor = ((UIButton)sender).FillColor;
            btDrawPoint.Visible = true;
            btDrawLine.Visible = true;
            btDrawCircle.Visible = true;
            btExitDraw.Visible = true;
        }

        private void btDrawAvoidPath_Click(object sender, EventArgs e)
        {
            drawGrueType = PathType.AvoidPath;
            drawPathColor = PathColor.gray;
            btDrawPoint.FillColor = ((UIButton)sender).FillColor;
            btDrawLine.FillColor = ((UIButton)sender).FillColor;
            btDrawCircle.FillColor = ((UIButton)sender).FillColor;
            btDrawPoint.Visible = true;
            btDrawLine.Visible = true;
            btDrawCircle.Visible = true;
            btExitDraw.Visible = true;
        }

        private void btDrawPoint_Click(object sender, EventArgs e)
        {
            switch (drawGrueType)
            {
                case PathType.None:
                    ShowWarningDialog("未选择路径类型");
                    break;
                case PathType.Glue:
                    zrf_hWindow1.DrawXldPathPoint(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.SpurtGlue:
                    zrf_hWindow1.DrawXldPathPoint(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.AvoidPath:
                    zrf_hWindow1.DrawXldPathPoint(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                default:
                    ShowWarningDialog("未选择路径类型");
                    break;
            }
        }

        private void btDrawLine_Click(object sender, EventArgs e)
        {
            switch (drawGrueType)
            {
                case PathType.None:
                    ShowWarningDialog("未选择路径类型");
                    break;
                case PathType.Glue:
                    zrf_hWindow1.DrawXldPathLine(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.SpurtGlue:
                    zrf_hWindow1.DrawXldPathLine(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.AvoidPath:
                    zrf_hWindow1.DrawXldPathLine(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                default:
                    ShowWarningDialog("未选择路径类型");
                    break;
            }
        }

        private void btDrawCircle_Click(object sender, EventArgs e)
        {
            switch (drawGrueType)
            {
                case PathType.None:
                    ShowWarningDialog("未选择路径类型");
                    break;
                case PathType.Glue:
                    zrf_hWindow1.DrawXldPathCircularArc(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.SpurtGlue:
                    zrf_hWindow1.DrawXldPathCircularArc(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                case PathType.AvoidPath:
                    zrf_hWindow1.DrawXldPathCircularArc(drawPathColor.ToString(), (int)drawGrueType);
                    break;
                default:
                    ShowWarningDialog("未选择路径类型");
                    break;
            }
        }

        private void btExitDraw_Click(object sender, EventArgs e)
        {
            btDrawPoint.Visible = false;
            btDrawLine.Visible = false;
            btDrawCircle.Visible = false;
            btExitDraw.Visible = false;
        }

        private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            ZrfFormControls.TextBoxNumValOnly_KeyPress(sender, e);
        }

        private void btShield_Click(object sender, EventArgs e)
        {
            if (zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield = !xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield;//取反
            btShield.FillColor = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield ? Color.Red : Color.Green;
            btShield.Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield ? "取消屏蔽" : "屏蔽";
            zrf_hWindow1.XldPaths[zrf_hWindow1.ActiveXldPathIndex].Color = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Shield ? "red" : xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Color.ToString();
            Zrf_hWindow1_RepaintEvent(null);
            zrf_hWindow1.Repaint();
        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (!((UITextBox)sender).Focused || zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            try
            {
                xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_DelayToOutGlue = double.Parse(((UITextBox)sender).Text);
            }
            catch
            {
                ((UITextBox)sender).Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_DelayToOutGlue.ToString();
            }
        }

        private void uiTextBox2_TextChanged(object sender, EventArgs e)
        {
            if (!((UITextBox)sender).Focused || zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            try
            {
                xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_OutGlueToStartMove = double.Parse(((UITextBox)sender).Text);
            }
            catch
            {
                ((UITextBox)sender).Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_OutGlueToStartMove.ToString();
            }
        }

        private void uiTextBox3_TextChanged(object sender, EventArgs e)
        {
            if (!((UITextBox)sender).Focused || zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            try
            {
                xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_StopGlueDelayTime = double.Parse(((UITextBox)sender).Text);
            }
            catch
            {
                ((UITextBox)sender).Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Delay_StopGlueDelayTime.ToString();
            }
        }

        private void uiTextBox4_TextChanged(object sender, EventArgs e)
        {
            if (!((UITextBox)sender).Focused || zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            try
            {
                xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Speed = double.Parse(((UITextBox)sender).Text);
            }
            catch
            {
                ((UITextBox)sender).Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].Speed.ToString();
            }
        }

        private void uiTextBox5_TextChanged(object sender, EventArgs e)
        {
            if (!((UITextBox)sender).Focused || zrf_hWindow1.ActiveXldPathIndex == -1)
            {
                return;
            }
            try
            {
                xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].PlaneHeight = double.Parse(((UITextBox)sender).Text);
            }
            catch
            {
                ((UITextBox)sender).Text = xldPathInfos[zrf_hWindow1.ActiveXldPathIndex].PlaneHeight.ToString();
            }
        }

        private void btGlueOutTest_Click(object sender, EventArgs e)
        {
            DoSingPathTest(true);
        }

        private void btCloseGlueTest_Click(object sender, EventArgs e)
        {
            DoSingPathTest(false);
        }

        private Page_3_TestWatchForm watchForm = new Page_3_TestWatchForm();

        private void DoSingPathTest(bool needGlue)
        {
            try
            {
                if (zrf_hWindow1.ActiveXldPathIndex > -1)
                {
                    controlMaster.DoSingelXldPathTest(zrf_hWindow1.XldPaths[zrf_hWindow1.ActiveXldPathIndex], xldPathInfos[zrf_hWindow1.ActiveXldPathIndex], needGlue, out HImage newImg, out List<XldPath> allXldPaths);
                    watchForm.ShowInfo(newImg, allXldPaths);
                    watchForm.Show();
                }
                else
                {
                    ShowWarningDialog("未选中路径");
                }
            }
            catch (Exception ee)
            {
                ShowErrorDialog(ee.Message);
            }
        }
    }

}
